<template>
  <div class="form-container">
    <el-row :gutter="20">
      <el-col
        :lg="{ span: 14, offset: 5 }"
        :md="{ span: 20, offset: 2 }"
        :sm="{ span: 20, offset: 2 }"
        :xl="{ span: 14, offset: 5 }"
        :xs="24"
      >
        <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
          <el-form-item label="标题" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <!-- <el-form-item label="副标题" prop="sub_name">
            <el-input v-model="form.sub_name" placeholder="分享链接时使用" />
          </el-form-item> -->
          <el-form-item label="举行日期" prop="date">
            <el-date-picker
              v-model="form.date"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD"
            />
            <!-- </vab-card> -->
          </el-form-item>
          <el-form-item label="地址名称" prop="building">
            <el-input v-model="form.building" />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" />
          </el-form-item>
          <!-- <el-form-item label="经度" prop="longitude">
            <el-input v-model="form.longitude" />
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="form.latitude" />
          </el-form-item> -->
          <el-form-item label="所属年份" prop="year">
            <el-date-picker
              v-model="form.year"
              format="YYYY"
              placeholder="选择年份"
              type="year"
              value-format="YYYY"
            />
          </el-form-item>
          <el-form-item label="往届回顾" prop="attach_metting">
            <el-select
              v-model="form.attach_metting"
              filterable
              multiple
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in select"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contact_name">
            <el-input v-model="form.contact_name" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contact_mobile">
            <el-input v-model="form.contact_mobile" />
          </el-form-item>
          <el-form-item label="传真" prop="contact_fax">
            <el-input v-model="form.contact_fax" />
          </el-form-item>
          <el-form-item label="邮箱" prop="contact_email">
            <el-input v-model="form.contact_email" />
          </el-form-item>
          <el-form-item label="二维码" prop="qrcode">
            <el-upload
              accept="image/png, image/jpeg"
              :action="uploadActionUrl"
              :on-success="handleQrcodeSuccess"
            >
              <el-button v-if="!form.qrcode" size="small" type="primary">
                点击上传
              </el-button>
              <img
                v-if="form.qrcode"
                :src="qrcodepath"
                style="max-width: 250px; max-height: 250px"
              />
            </el-upload>
          </el-form-item>
          <el-form-item label="会议主题" prop="theme">
            <el-input v-model="form.theme" />
          </el-form-item>
          <el-form-item
            ref="welcomespeechRef"
            class="vab-quill-content"
            label="会议介绍"
            :options="welcomespeechoptions"
            prop="introduce"
          >
            <!-- <vab-quill
              ref="welcome_speech_quill"
              v-model="form.welcome_speech"
              :min-height="400"
              :options="welcomespeechoptions"
            /> -->
            <TextEditor
              v-if="editorShow"
              :content="form.introduce"
              field="introduce"
              @changeValue="changeValue"
            />
          </el-form-item>
          <el-form-item
            ref="welcomespeechRef"
            class="vab-quill-content"
            label="会议日程介绍"
            :options="welcomespeechoptions"
            prop="date_introduce"
          >
            <!-- <vab-quill
              ref="welcome_speech_quill"
              v-model="form.welcome_speech"
              :min-height="400"
              :options="welcomespeechoptions"
            /> -->
            <TextEditor
              v-if="editorShow"
              :content="form.date_introduce"
              field="date_introduce"
              @changeValue="changeValue"
            />
          </el-form-item>
          <el-form-item label="参会对象" prop="participant">
            <TextEditor
              v-if="editorShow"
              :content="form.participant"
              field="participant"
              @changeValue="changeValue"
            />
          </el-form-item>
          <el-form-item label="会议安排" prop="arrangement">
            <TextEditor
              v-if="editorShow"
              :content="form.arrangement"
              field="arrangement"
              @changeValue="changeValue"
            />
          </el-form-item>
          <el-form-item label="会议费用" prop="money">
            <TextEditor
              v-if="editorShow"
              :content="form.money"
              field="money"
              @changeValue="changeValue"
            />
          </el-form-item>

          <el-form-item label="word版资料" prop="word">
            <el-upload
              accept=".doc,.docx"
              :action="uploadActionUrl"
              :on-success="handleWordSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <a v-if="form.word" :href="wordpath">下载word版资料</a>
          </el-form-item>

          <el-form-item label="PPT专用模板" prop="ppt">
            <el-upload
              accept=".ppt,.pptx"
              :action="uploadActionUrl"
              :on-success="handlePPTSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <a v-if="form.ppt" :href="pptpath">下载PPT专用模板</a>
          </el-form-item>
          <el-form-item label="pdf通知公函" prop="pdf">
            <el-upload
              accept=".pdf"
              :action="uploadActionUrl"
              :on-success="handlePDFSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <a v-if="form.pdf" :href="pdfpath">下载pdf通知公函</a>
          </el-form-item>
          <!-- <el-form-item
            class="vab-quill-content"
            label="组织架构"
            prop="jiagou"
          >
            <TextEditor
              v-if="editorShow"
              :content="form.jiagou"
              field="jiagou"
              @changeValue="changeValue"
            />
          </el-form-item> -->
        </el-form>
      </el-col>
    </el-row>

    <div class="pay-button-group">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </div>
  </div>
  <el-upload
    ref="welcomespeechuploadRef"
    accept="image/png, image/jpeg"
    :action="uploadActionUrl"
    :on-success="handleWelcomeSpeechSuccess"
    :show-file-list="false"
  />
  <el-upload
    ref="jiagouuploadRef"
    accept="image/png, image/jpeg"
    :action="uploadActionUrl"
    :on-success="handleJiagouSuccess"
    :show-file-list="false"
  />
</template>

<script>
  import { defineComponent, getCurrentInstance, reactive, toRefs } from 'vue'
  // import VabQuill from '@/extra/VabQuill'
  import { doEdit, getList, getSelect } from '@/api/metting'
  import { baseURL, HOST } from '@/config'
  import TextEditor from './TextEditor'

  export default defineComponent({
    // components: { VabQuill, TextEditor },
    components: { TextEditor },
    props: {
      mettingId: {
        type: Number,
        required: true,
      },
    },
    emits: ['change-step'],
    setup(props) {
      const { proxy } = getCurrentInstance()

      const state = reactive({
        select: [],
        wordpath: '',
        welcome_speech_quill: null,
        welcomespeechuploadRef: null,
        jiagouuploadRef: null,
        uploadRef: null,
        formRef: null,
        editorShow: false,
        form: {
          name: '',
          introduce: '',
          year: '',
          id: props.mettingId,
          attcach_metting: [],
          sub_name: '',
          address: '',
          building: '',
          date: '',
          theme: '',
          contact_name: '',
          contact_mobile: '',
          contact_fax: '',
          contact_email: '',
          qrcode: '',
          participant: '',
          arrangement: '',
          money: '',
          word: '',
          ppt: '',
          pdf: '',
          // longitude: '',
          // latitude: '',
        },
        qrcodepath: '',
        uploadActionUrl: baseURL + 'upload/ajaxUploads',

        detail: {},
        xuzhioptions: {
          theme: 'snow',
          bounds: document.body,
          debug: 'warn',
          modules: {
            toolbar: {
              container: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                [{ size: ['small', false, 'large', 'huge'] }],
                [{ color: [] }, { background: [] }],
                ['blockquote', 'code-block'],
                [{ list: 'ordered' }, { list: 'bullet' }],
                [{ script: 'sub' }, { script: 'super' }],
                [{ indent: '-1' }, { indent: '+1' }],
                [{ align: [] }],
                [{ direction: 'rtl' }],
                [{ font: [] }],
                ['clean'],
              ],
            },
          },
        },
        welcomespeechoptions: {
          theme: 'snow',
          bounds: document.body,
          debug: 'warn',
          modules: {
            toolbar: {
              container: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                [{ size: ['small', false, 'large', 'huge'] }],
                [{ color: [] }, { background: [] }],
                ['blockquote', 'code-block'],
                [{ list: 'ordered' }, { list: 'bullet' }],
                [{ script: 'sub' }, { script: 'super' }],
                [{ indent: '-1' }, { indent: '+1' }],
                [{ align: [] }],
                [{ direction: 'rtl' }],
                [{ font: [] }],
                ['clean'],
                // ['image'],
              ],
              // handlers: {
              //   image: () => {
              //     state['welcomespeechuploadRef'].uploadRef.handleClick()
              //   },
              // },
            },
          },
        },
        jiagouoptions: {
          theme: 'snow',
          bounds: document.body,
          debug: 'warn',
          modules: {
            toolbar: {
              container: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ header: [1, 2, 3, 4, 5, 6, false] }],
                [{ size: ['small', false, 'large', 'huge'] }],
                [{ color: [] }, { background: [] }],
                ['blockquote', 'code-block'],
                [{ list: 'ordered' }, { list: 'bullet' }],
                [{ script: 'sub' }, { script: 'super' }],
                [{ indent: '-1' }, { indent: '+1' }],
                [{ align: [] }],
                [{ direction: 'rtl' }],
                [{ font: [] }],
                ['clean'],
                ['image'],
              ],
              handlers: {
                image: () => {
                  state['jiagouuploadRef'].uploadRef.handleClick()
                },
              },
            },
          },
        },
        rules: {
          name: [
            { required: true, message: '请输入会议名称', trigger: 'blur' },
          ],
          // sub_name: [
          //   { required: true, message: '请输入会议副标题', trigger: 'blur' },
          // ],
          year: [
            { required: true, message: '请选择所属年份', trigger: 'blur' },
          ],
          building: [
            { required: true, message: '请输入地址名称', trigger: 'blur' },
          ],
          address: [
            { required: true, message: '请输入详细地址', trigger: 'blur' },
          ],
          date: [
            { required: true, message: '请选择举行日期', trigger: 'blur' },
          ],
          theme: [
            { required: true, message: '请输入会议主题', trigger: 'blur' },
          ],
          introduce: [
            { required: true, message: '请输入会议介绍', trigger: 'blur' },
          ],
          // longitude: [
          //   { required: true, message: '请输入经度', trigger: 'blur' },
          // ],
          // latitude: [
          //   { required: true, message: '请输入纬度', trigger: 'blur' },
          // ],
        },
      })

      const handleSubmit = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await doEdit(state.form)
            proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
            close()
          }
        })
      }

      // const handleWelcomeSpeechSuccess = (response) => {
      //   console.log(state.welcome_speech_quill)
      //   if (response.code == 0) {
      //     let path = HOST + response.data[0].path
      //     state.form.welcome_speech += "<img src='" + path + "'>"
      //     // let quill = state['xuzhiRef']
      //     // console.log(quill)
      //     // // 获取光标所在位置
      //     // let length = quill.getSelection().index
      //     // // 插入图片 res.url为服务器返回的图片地址
      //     // quill.insertEmbed(length, 'image', path)
      //     // // 调整光标到最后
      //     // quill.setSelection(length + 1)
      //   }
      // }
      const handleJiagouSuccess = (response) => {
        if (response.code == 0) {
          let path = HOST + response.data[0].path
          state.form.jiagou += "<img src='" + path + "'>"
          // let quill = state['xuzhiRef']
          // console.log(quill)
          // // 获取光标所在位置
          // let length = quill.getSelection().index
          // // 插入图片 res.url为服务器返回的图片地址
          // quill.insertEmbed(length, 'image', path)
          // // 调整光标到最后
          // quill.setSelection(length + 1)
        }
      }
      const fetchData = async () => {
        const {
          data: { list },
        } = await getList({ id: state.form.id })
        state.detail = list[0]
        state.form.name = list[0].name
        state.form.welcome_speech = list[0].welcome_speech
        state.form.jiagou = list[0].jiagou
        state.form.xuzhi = list[0].xuzhi
        state.form.year = list[0].year
          ? list[0].year
          : new Date().getFullYear().toString()

        state.form.attach_metting = list[0].attach_metting
        state.form.sub_name = list[0].sub_name
        state.form.address = list[0].address
        // state.form.longitude = list[0].longitude
        // state.form.latitude = list[0].latitude
        state.form.building = list[0].building
        state.form.date = [list[0].start_date, list[0].end_date]
        state.form.contact_name = list[0].contact_name
        state.form.contact_mobile = list[0].contact_mobile
        state.form.contact_fax = list[0].contact_fax
        state.form.contact_email = list[0].contact_email
        state.form.theme = list[0].theme
        state.form.introduce = list[0].introduce
        state.form.date_introduce = list[0].date_introduce
        state.form.participant = list[0].participant
        state.form.arrangement = list[0].arrangement
        state.form.money = list[0].money
        state.form.word = list[0].word
        state.wordpath = HOST + list[0].word
        state.form.pdf = list[0].pdf
        state.pdfpath = HOST + list[0].pdf
        state.form.ppt = list[0].ppt
        state.pptpath = HOST + list[0].ppt
        state.form.qrcode = list[0].qrcode
        state.qrcodepath = HOST + list[0].qrcode

        state.editorShow = true
      }
      const handleWordSuccess = (response) => {
        if (response.code == 0) {
          state.form.word = response.data[0].path
          state.wordpath = HOST + response.data[0].path
        }
      }
      const handlePPTSuccess = (response) => {
        if (response.code == 0) {
          state.form.ppt = response.data[0].path
          state.pptpath = HOST + response.data[0].path
        }
      }
      const handlePDFSuccess = (response) => {
        if (response.code == 0) {
          state.form.pdf = response.data[0].path
          state.pdfpath = HOST + response.data[0].path
        }
      }
      const handleQrcodeSuccess = (response) => {
        if (response.code == 0) {
          state.form.qrcode = response.data[0].path
          state.qrcodepath = HOST + response.data[0].path
          console.log(state.form.qrcode)
          console.log(state.qrcodepath)
        }
      }
      const fetchSelect = async () => {
        const {
          data: { list },
        } = await getSelect({})
        state.select = list
      }
      const changeValue = (value, fieldName) => {
        state.form[fieldName] = value
      }
      fetchData()
      fetchSelect()
      return {
        ...toRefs(state),
        handleSubmit,
        fetchData,
        // handleWelcomeSpeechSuccess,
        handleJiagouSuccess,
        fetchSelect,
        changeValue,
        handleWordSuccess,
        handlePPTSuccess,
        handlePDFSuccess,
        handleQrcodeSuccess,
      }
    },
    methods: {
      handleWelcomeSpeechSuccess(response) {
        this.$nextTick(() => {
          console.log(this.$refs['vab-quill'])
          console.log(this.$refs['welcome_speech_quill'].Quill)
          //用法 this.$refs["vab-quill"].Quill.quill的底层的方法;
          this.$refs['welcome_speech_quill'].Quill.getLength()
        })
        if (response.code == 0) {
          let path = HOST + response.data[0].path
          this.form.welcome_speech += "<img src='" + path + "'>"
          // let quill = state['xuzhiRef']
          // console.log(quill)
          // // 获取光标所在位置
          // let length = quill.getSelection().index
          // // 插入图片 res.url为服务器返回的图片地址
          // quill.insertEmbed(length, 'image', path)
          // // 调整光标到最后
          // quill.setSelection(length + 1)
        }
      },
    },
  })
</script>

<style lang="scss" scoped>
  .pay-button-group {
    display: block;
    margin: 20px auto;
    text-align: center;
  }
  :deep() {
    .el-upload-list {
      display: none;
    }
  }
</style>
